package erp

import (
	"context"
	"encoding/json"
	"errors"
	"strconv"
	"strings"

	"mall/common/utils/pointy"
	"mall/service/backend/common/erp"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetErpOrderStatusListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetErpOrderStatusListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetErpOrderStatusListLogic {
	return &BackendGetErpOrderStatusListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 查询订单状态    主动同步本地
func (l *BackendGetErpOrderStatusListLogic) BackendGetErpOrderStatusList(in *backend.GetErpOrderStatusListReq) (*backend.GetErpOrderStatusListResp, error) {
	// 参考文档： https://open.hupun.com/api-doc/erp/b2c/trades/erp/status
	if in.TradeIds == nil || len(strings.TrimSpace(*in.TradeIds)) == 0 {
		return nil, nil
	}
	shopNick := l.svcCtx.Config.Erp.ShopNick
	if in.ShopNick != nil && len(strings.TrimSpace(*in.ShopNick)) > 0 {
		shopNick = *in.ShopNick
	}
	erpMap := map[string]string{
		"shop_nick": shopNick,
		"shop_type": strconv.FormatUint(l.svcCtx.Config.Erp.ShopType, 10),
		"trade_ids": *in.TradeIds,
	}
	path := "/erp/b2c/trades/erp/status"
	erpClient := erp.NewErp(l.svcCtx.Config.Erp.AppKey, l.svcCtx.Config.Erp.Secret, l.svcCtx.Config.Erp.Url, path)
	err := erpClient.GetSign(erpMap)
	if err != nil {
		return nil, err
	}
	resMap, err := erpClient.CallErpApi()
	if err != nil {
		return nil, err
	}
	res := resMap["response"].(string)
	var m = map[string]any{}
	json.Unmarshal([]byte(res), &m)
	if !resMap["success"].(bool) {
		return nil, errors.New("kong")
	}

	var orderList []*backend.ErpOrderStatusInfo
	for _, v := range m["statuses"].(any).([]any) {
		value := v.(map[string]any)
		orderList = append(orderList, &backend.ErpOrderStatusInfo{
			OrderSn:     pointy.GetPointer(value["tid"].(string)),
			Status:      pointy.GetPointer(value["status"].(string)),
			ExpressName: pointy.GetPointer(value["express"].(string)),
			ExpressCode: pointy.GetPointer(value["express_code"].(string)),
			Waybill:     pointy.GetPointer(value["waybill"].(string)),
		})
	}
	return &backend.GetErpOrderStatusListResp{
		List: orderList,
	}, nil
}
